package ac.zlf.springmybatis.admin.bjui.controller.common;

import ac.zlf.springmybatis.base.entity.User;
import ac.zlf.springmybatis.core.mybatis.domain.Page;
import ac.zlf.springmybatis.core.mybatis.domain.PageRequest;
import ac.zlf.springmybatis.core.mybatis.domain.Sort;
import ac.zlf.springmybatis.vo.PageParams;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by Administrator on 2017/4/22 0022.
 */
@Controller
public class BaseController {
    public User getUser(HttpServletRequest request){
        return new User();
    }

    /**
     * 处理分页数据
     * @param page          Page对象
     * @param pageParams    分页参数对象
     * @param request       HttpServletRequest对象
     */
    public void handlePageData(Page page, PageParams pageParams, HttpServletRequest request) {
        if(page == null) {
            request.setAttribute("total", 0);
            request.setAttribute("pageSize", pageParams.getPageSize());
            request.setAttribute("pageCurrent", pageParams.getPageCurrent());
            request.setAttribute("orderField", pageParams.getOrderField());
            request.setAttribute("orderDirection", pageParams.getOrderDirection());
        }else {
            request.setAttribute("list", page);
            request.setAttribute("total", page.getTotalElements());
            request.setAttribute("pageSize", page.getPageSize());
            request.setAttribute("pageCurrent", pageParams.getPageCurrent());
            request.setAttribute("orderField", pageParams.getOrderField());
            request.setAttribute("orderDirection", pageParams.getOrderDirection());
        }
    }

    /**
     * 根据传入的PageParams对象得到PageRequest对象
     * @param pageParams
     * @return
     */
    public static PageRequest handlePageParams(PageParams pageParams) {
        PageRequest pageRequest = null;
        //排序字段与排序方式均不为空
        if(!StringUtils.isEmpty(pageParams.getOrderField()) && !StringUtils.isEmpty(pageParams.getOrderDirection())) {
            if(pageParams.getOrderDirection().equals("asc")) {
                pageRequest = new PageRequest(pageParams.getPageCurrent(), pageParams.getPageSize(), Sort.Direction.ASC, pageParams.getOrderField());
            } else if(pageParams.getOrderDirection().equals("desc")) {
                pageRequest = new PageRequest(pageParams.getPageCurrent(), pageParams.getPageSize(), Sort.Direction.DESC, pageParams.getOrderField());
            } else {
                pageRequest = new PageRequest(pageParams.getPageCurrent(), pageParams.getPageSize());
            }
        } else {
            pageRequest = new PageRequest(pageParams.getPageCurrent(), pageParams.getPageSize());
        }
        return pageRequest;
    }
}
